package com.zhanglu.fun.services.authentication.token;

import com.zhanglu.fun.services.authentication.bean.request.TokenRequest;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhanglu
 * @description
 * @date 2017/8/28 20:14
 */
@RestController
@Slf4j
public class TokenSecureRouter {

    @Autowired
    private TokenSecureService tokenSecureService;

    @ApiOperation(value = "获得token", notes = "根据帐号密码获取token，返回是null说明用户不存在或者token不存在")
    @ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "用户帐号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String", paramType = "query") })
    @ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = String.class) })
    @GetMapping("/fun/secure/token")
    public String getToken(@RequestParam("username") String username, @RequestParam("password") String password) {
        log.info("getToken params:[username is {} | password is {}]", username, password);
        return tokenSecureService.getToken(username, password);
    }

    @ApiOperation(value = "注册token,即登录方法", notes = "注册token，返回token，如果返回null，说明token不存在或者用户不存在")
    @ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = String.class) })
    @PutMapping("/fun/secure/token")
    public String registerToken(@RequestBody TokenRequest tokenRequest) {
        log.info("registerToken params:[username is {} | password is {}]", tokenRequest.getUsername(), tokenRequest.getPassword());
        return tokenSecureService.registerToken(tokenRequest.getUsername(), tokenRequest.getPassword());
    }

    @ApiOperation(value = "更新token", notes = "用于刷新token，因为本地token时间和db中token时间是有误差的，本地到期之后查询db中，如果没到期就重新生成token返回。返回null说明token不存在或者已经过期")
    @ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = String.class) })
    @PostMapping("/fun/secure/token")
    public String refreshToken(@RequestBody TokenRequest tokenRequest) {
        log.info("refreshToken params:[token is {}]", tokenRequest.getToken());
        return tokenSecureService.refreshToken(tokenRequest.getToken());
    }

    @ApiOperation(value = "删除token", notes = "删除token")
    @ApiImplicitParams({ @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "String", paramType = "query"), })
    @ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = String.class) })
    @DeleteMapping("/fun/secure/token")
    public boolean deleteToken(@RequestParam("token") String token) {
        log.info("deleteToken params:[token is {}]", token);
        return tokenSecureService.deleteToken(token);
    }

}
